﻿using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace BodaNetCommunications.Cores;
public static class NetHelper
{
    public static bool PintHost(string ip, int port, bool needTcp = false, int trialCount = 2, int timeout = 500)
    {
        bool pingRes = false;
        for (int i = 0; i < trialCount; i++)
        {
            using Ping pingSender = new Ping();
            PingReply replyAsync = pingSender.SendPingAsync(ip, timeout).GetAwaiter().GetResult();
            if (replyAsync.Status == IPStatus.Success)
            {
                if (needTcp)
                {
                    using TcpClient tcpClient = new TcpClient();
                    IAsyncResult result = tcpClient.BeginConnect(ip, port, null, null);
                    bool success = result.AsyncWaitHandle.WaitOne(timeout, true);

                    if (tcpClient.Connected)
                    {
                        pingRes = true;
                        break;
                    }
                    tcpClient.Close();
                }
                else
                {
                    pingRes = true;
                    break;
                }
            }
        }
        return pingRes;
    }
}